package com.mszlu.blog.admin.service;


import com.mszlu.blog.admin.pojo.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

//@Component
@Service
public class SecurityUserService implements UserDetailsService {
    @Autowired
    AdminService adminService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        /*
        *登录的时候，把username传递到这里
        * 通过username 查询admin表，如果admin存在进行密码认证。我们本身不进行密码认证，而是将密码告诉spring security。
        * 如果不存在，返回null，认证失败。
        */
        Admin admin = adminService.findAdminByUsername(username);
        if (admin==null){
            //登陆失败
            return null;
        }
        //存在，进行密码认证，spring security实现。
        //UserDetails一个接口，User实现类。
        //(String username, String password, Collection<? extends GrantedAuthority> authorities)
        UserDetails userDetails=new User(username,admin.getPassword(),new ArrayList<>());
        return userDetails;

    }
}
